﻿#encoding: utf-8
=begin

Usage:      This ruby file will print crmeb orders for specific duration`
arguments:  ruby print-orders.rb [start_time backward_hours] [-s]'
Example:    ruby print-orders.rb 2019-07-09 08:00 24'
Comment:    无参数调用 ruby print-orders.rb, 相当于ruby order-man.rb current_time 24
            从现在倒推的24小时之内, 注意这个逻辑和order_man是有区别的，后者脑洞结构异常

=end

load 'rds_api.rb'
load 'wechat_api.rb'
load 'crmeb_utils.rb'

etime = ( ARGV[0] && ARGV[1] ) ? Time.parse("#{ARGV[0]} #{ARGV[1]}") : Time.now
bhours = ARGV[2] ? ARGV[2].to_i : 24
stime = etime - bhours*3600 + 1 #leave one second

def pickup_pages_during stime, etime

  list = []
  res = @rds.query "select oid, add_time, line, phone, order_code, text from crmeb.eb_pickup_book where add_time >= #{stime.to_i} and add_time <= #{etime.to_i};" #using unix_timestamp
  res.each do |r|

    page = {}

    page.store "id", "#{r['oid']}"
    page.store "time", "#{Time.at(r['add_time']).strftime("%m%d%H%M")}"
    page.store "line", "#{r['line']}"
    page.store "phone", "#{r['phone']}"
    page.store "text", "#{r['text']}"
    page.store "code", r['order_code'].to_s #防止空值

    list += [page]

  end

  return list

end

pages = pickup_pages_during stime, etime
pages.each do |page|
  dir = OS.windows? ? ".\\orders\\incoming\\" : "./orders/incoming/"
  fn = dir + page['time'] + "-order-" + page['line'] +  "-" + page['phone'] + "-" + page['code'] + ".txt"
  processed_dir = OS.windows? ? ".\\orders\\converted\\" : "./orders/converted/"
  processed_txt = processed_dir + page['time'] + "-order-" + page['line'] +  "-" + page['phone'] + "-" + page['code'] + ".txt"
  send_bot_message(  page['text'], ['foodcherry']) if !File.exist?(processed_txt)
  File.open(fn,"w:UTF-8") { |f| f.write page['text'] } #if !fn.include?("-order-X")
end
